package com.example.network.JSON_parsing;

import com.example.network.entity.Person;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class JSON_Native {
    /**
     * 解析对象
     * @param json
     * @return
     */
    public Person ObjectanalysisTest(String json) {
        Person person = new Person();
        try {
            JSONObject jsonObject = new JSONObject(json);
            person.setId(jsonObject.getInt("id"));
            person.setName(jsonObject.getString("name"));
            person.setAge(jsonObject.getInt("age"));
            return person;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析对象数组
     * @param json
     * @return
     */
    public ArrayList<Person> ArrayanalysisTest(String json) {
        ArrayList persons = new ArrayList<Person>();
        try{
            JSONArray jsonArray = new JSONArray(json);
            for(int i = 0;i < jsonArray.length();i++){
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                Person person = new Person();
                person.setId(jsonObject.getInt("id"));
                person.setName(jsonObject.getString("name"));
                person.setAge(jsonObject.getInt("age"));
                persons.add(person);
            }
        }catch (Exception e){e.printStackTrace();}
        return persons;
    }
}
